using MultiAgentsClient.Service.WorkflowEngine.BaseNodes;
using MultiAgentsClient.Shared;
using MultiAgentsShared;
using static MultiAgentsServer.Scripts.Shared.ModelConsts;

namespace MultiAgentsClient.Service.WorkflowEngine.BuiltInNodes;

/// <summary>
/// No toolcall for llm request
/// </summary>
public class NodeLlmRequest : NodeRequestToService
{
    public List<string> messages;
    public string gptModel;
    public float temperature;

    public NodeLlmRequest(string nodeId) : base(nodeId) { }
}

public class NodeLlmResponse : NodeResponseFromService
{
    public string llmResult;

    public NodeLlmResponse(string nodeId) : base(nodeId) { }
}

[NodeGraphPortDef(1, 1)]
public class LlmNode : ServiceDependentNode<NodeLlmRequest, NodeLlmResponse>
{
    [NodeGraphParam] public List<LlmMessageSimp> Messages;
    private List<LlmMessageSimp> MessagesRuntime => InsertVariable(Messages);
    [NodeGraphParam] public LlmModels ModelEnum;
    [NodeGraphParam] public float Temperature;

    //TODO: the SetVar method should be code generated, to ensure name correctness
    [NodeGraphOutput] private string LlmResponse;

    public LlmNode() : base()
    {
    }

    protected override NodeOutcome ServiceResponseHandler(NodeLlmResponse cmd)
    {
        Debug.LogLine("LlmNodeResponse:" + cmd.llmResult);
        LlmResponse = cmd.llmResult;
        runtimeContext.SetVar(Id, () => LlmResponse);
        return new NodeOutcome(NodeOutcomeStatus.Success, 0);
    }

    protected override void SendRequestToService()
    {
        var nodeLlmRequest = new NodeLlmRequest(Id)
        {
            temperature = Temperature,
            gptModel = modelInfos[ModelEnum].ModelName,
            messages = []
        };

        foreach (var message in MessagesRuntime)
        {
            nodeLlmRequest.messages.Add(SerializableObjectBase.ConvertToJson(message));
        }

        EventBus.Publish(nodeLlmRequest);
    }
}
